package com.lv.controller;

import com.lv.dao.UserMapper;
import com.lv.pojo.Cart;
import com.lv.pojo.User;

import com.lv.pojo.Watch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
public class RouterCon {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserMapper userMapper;

    //首页跳转
    @RequestMapping({"/","/index"})
    public String index(){
        return "index";
    }
    //跳转到登录页
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
//未认证请求
    @RequestMapping("/please")
    public String pleaseLogin(Model model){
        model.addAttribute("msg","<script>alert('请登录后再操作')</script>");
        return "login";
    }
    //跳转到商城页
    @RequestMapping("/toShop")
    public String toShop(Model model) {
        //获取所有商品信息
        List<Watch> allWatch = userMapper.getAllWatch();
        model.addAttribute("list",allWatch);
        return "shop";
    }
    //处理登录失败的请求
    @RequestMapping("/failLogin")
    public String failLogin(Model model){
        model.addAttribute("msg","<script>alert('账号或密码错误！')</script>");
        return "login";
    }
    //处理注册请求
    @RequestMapping("/toRegister")
    public String addUser(User user, Model model){
        //先通过注册的用户名查找是否已经被注册
        User userByName = userMapper.getUserByName(user.getUsername());
        if(userByName==null){
            //如果未被注册，加密密码
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            //连接数据库添加用户
            int i = userMapper.addUser(user);
            if(i>0){//添加成功
                model.addAttribute("msg","<script>alert('注册成功，请登录！')</script>");
                return "login";
            }
            //添加失败
            model.addAttribute("msg","<script>alert('注册失败，请重新注册！')</script>");
            return "login";
        }
        //用户名已经被注册
        model.addAttribute("msg","<script>alert('该用户名已被注册！')</script>");
        return "login";
    }
    //跳转至用户信息页面
    @RequestMapping("/toUser")
    public String toUser(Model model){
        String name= SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userMapper.getUserByName(name);
        model.addAttribute("user",user);
        return "user";
    }
    //忘记密码
    @RequestMapping("/forget")
    public String forget(){
        return "forget";
    }

    //找回密码
    @RequestMapping("/find")
    public String find(User user, Model model){
        User userByName = userMapper.getUserByName(user.getUsername());
        if(userByName==null){
           model.addAttribute("msg","<script>alert('用户名不存在')</script>") ;
           return "forget";
        }else{
            if(userByName.getPhoneNumber().equals(user.getPhoneNumber())){
                user.setPassword(passwordEncoder.encode(user.getPassword()));
                int i = userMapper.upUser(user);
                if(i>0){
                    model.addAttribute("msg","<script>alert('修改成功，请登录')</script>") ;
                    return "login";
                }else {
                    model.addAttribute("msg","<script>alert('修改失败，请重试')</script>") ;
                    return "forget";
                }
            }
            model.addAttribute("msg","<script>alert('电话信息错误')</script>") ;
            return "forget";
        }
    }

    @RequestMapping("toAdmin")
    public String toadmin(){
        return "admin";
    }
    @RequestMapping("toWatchList")
    public String towatchlist(Model model){
        List<Watch> allWatch = userMapper.getAllWatch();
        model.addAttribute("list",allWatch);
        return "watchlist";
    }

    @RequestMapping("toAddWatch")
    public String toAddWatch(Model model){
        return "addWatch";
    }

    @RequestMapping("/addWatch")
    public String addWatch(Watch watch, @RequestParam("file") MultipartFile file, Model model){
        if(file.isEmpty()){
            model.addAttribute("msg","<script>alert('请添加图片')</script>");
            return towatchlist(model);
        }
        String filename = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("\\") + 1);
        String filetype=filename.substring(filename.lastIndexOf(".")+1);
        if(filetype.equals("jpg")||filetype.equals("png")||filetype.equals("jpeg")){
            String filepath="/local/img";
            try {
                file.transferTo(new File(filepath+"/"+filename));
            } catch (Exception e) {
                e.printStackTrace();
                model.addAttribute("msg","<script>alert('上传失败，请重试')</script>");
                return toAddWatch(model);
            }
            watch.setImg_href(filename);
            int i = userMapper.addWatch(watch);
            if(i>0){
                model.addAttribute("msg","<script>alert('添加成功')</script>");
                return towatchlist(model);
            }
            model.addAttribute("msg","<script>alert('添加失败，请重试')</script>");
            return toAddWatch(model);
        }
        model.addAttribute("msg","<script>alert('图片格式不支持！！')</script>");
        return toAddWatch(model);
    }
    @RequestMapping("/deWatch/{id}")
    public String deWatch(@PathVariable Integer id, RedirectAttributes attributes){
        int i = userMapper.deWatch(id);
        attributes.addFlashAttribute("msg","<script>alert('删除成功')</script>");
        return "redirect:/toWatchList";
    }

    @RequestMapping("/toUpWatch/{id}")
    public String toUpWatch(@PathVariable Integer id,Model model){
        Watch watch = userMapper.getWatchById(id);
        model.addAttribute("watch",watch);
        return "upWatch";
    }
    @RequestMapping("/upWatch")
    public String upWatch(Watch watch,@RequestParam("file") MultipartFile file,Model model){
        if(!file.isEmpty()){
            String filename = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("\\") + 1);
            String filetype=filename.substring(filename.lastIndexOf(".")+1);
            if(filetype.equals("jpg")||filetype.equals("png")||filetype.equals("jpeg")){
                String filepath="/local/img";
                try {
                    file.transferTo(new File(filepath+"/"+filename));

                } catch (IOException e) {
                    e.printStackTrace();
                    model.addAttribute("msg","<script>alert('图片上传失败，请重试')</script>");
                    return toUpWatch(watch.getWatch_id(),model);
                }
                watch.setImg_href(filename);
            }else {
                model.addAttribute("msg","<script>alert('图片格式错误')</script>");
                return toUpWatch(watch.getWatch_id(),model);
            }
        }
        int i = userMapper.upWatch(watch);
        if(i>0){
            model.addAttribute("msg","<script>alert('修改成功')</script>");
            return towatchlist(model);
        }
        model.addAttribute("msg","<script>alert('修改失败，请重试')</script>");
        return towatchlist(model);
    }
}
